package com.example.travel_front.Fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.travel_front.Adapter.MessageAdapter;
import com.example.travel_front.Model.Message;
import com.example.travel_front.R;
import com.example.travel_front.Utils.WebSocketClient;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class MessageFragment extends Fragment {
    private RecyclerView recyclerView;
    private MessageAdapter adapter;
    private List<Message> messages;
    private WebSocketClient webSocketClient;
    private static final String serverUrl = "http://121.40.98.114:15000/chat";

    private static final String ARG_CHAT_ID = "chat_id";

    public static MessageFragment newInstance(int chatId) {
        MessageFragment fragment = new MessageFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_CHAT_ID, chatId);
        fragment.setArguments(args);
        return fragment;
    }


    @SuppressLint("NotifyDataSetChanged")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.message_detail, container, false);

        recyclerView = view.findViewById(R.id.chat_recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        messages = getMessages(); // 这个方法需要实现数据的获取
        adapter = new MessageAdapter(messages);
        recyclerView.setAdapter(adapter);

        EditText messageEditText = view.findViewById(R.id.message_input);
        ImageView sendImageView = view.findViewById(R.id.button_send);

        sendImageView.setOnClickListener(v -> {
            String messageText = messageEditText.getText().toString();
            if (!messageText.isEmpty()) {
                Message message = new Message(messageText, true,Integer.parseInt(ARG_CHAT_ID)); // 假设发送的消息是由当前用户发送
                messages.add(message);
                adapter.notifyDataSetChanged();
                recyclerView.scrollToPosition(messages.size() - 1);
                webSocketClient.sendMessage(messageText);
                messageEditText.setText("");
            }
        });

        initiateWebSocket();



        return view;
    }

    private void initiateWebSocket() {
        WebSocketListener webSocketListener = new WebSocketListener() {
            @Override
            public void onOpen(@NonNull WebSocket webSocket, @NonNull Response response) {
                // 可以在这里处理连接打开事件
            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onMessage(@NonNull WebSocket webSocket, @NonNull String text) {
                requireActivity().runOnUiThread(() -> {
                    messages.add(new Message(text, false,Integer.parseInt(ARG_CHAT_ID))); // 假设所有接收的消息都不是由当前用户发送
                    adapter.notifyDataSetChanged();
                    recyclerView.scrollToPosition(messages.size() - 1);
                });
            }

            @Override
            public void onClosed(@NonNull WebSocket webSocket, int code, @NonNull String reason) {
                // 可以在这里处理连接关闭事件
            }

            @Override
            public void onFailure(@NonNull WebSocket webSocket, @NonNull Throwable t, Response response) {
                // 可以在这里处理连接失败事件
            }
        };

        webSocketClient = new WebSocketClient();
        webSocketClient.start(serverUrl, webSocketListener);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        webSocketClient.close(); // 关闭 WebSocket 连接
    }

    private List<Message> getMessages() {
        // TODO: 实现数据获取逻辑
        List<Message> list = new ArrayList<>();
        list.add(new Message("Hello!", true,1)); // Sent by the user
        list.add(new Message("Hi, how can I assist you today?", false,1)); // Received
        return list;
    }
}
